﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using CommonSense.UI.MVVM.ViewModels;
using System.Windows.Input;
using System.ComponentModel;

namespace CommonSense.UI.Shell.ViewModels
{
    public abstract class BaseViewModel : NotifyPropertyChangedBaseModel
    {
        public event EventHandler<CancelEventArgs> Closing;
        public event EventHandler Closed;
        public event EventHandler IsDirtyChanged;

        private string title;
        private bool isDirty;
        private FrameworkElement view;

        public string Title
        {
            get { return this.title; }
            protected set
            {
                if (this.title != value)
                {
                    this.title = value;
                    this.OnPropertyChanged();
                }
            }
        }

        public bool IsDirty
        {
            get { return this.isDirty; }
            set
            {
                if (this.isDirty != value)
                {
                    this.isDirty = value;
                    this.OnPropertyChanged();
                    if (this.IsDirtyChanged != null)
                    {
                        this.IsDirtyChanged(this, EventArgs.Empty);
                    }
                }
            }
        }

        public FrameworkElement View
        {
            get { return this.view; }
            internal set
            {
                this.view = value;
                this.view.Loaded += (s, e) => OnLoaded();
                this.view.Unloaded += (s, e) => OnUnloaded();
            }
        }

        public RelayCommand CloseCommand
        {
            get;
            private set;
        }

        public BaseViewModel()
        {
            this.CloseCommand = new RelayCommand(this.Close);
        }

        protected internal virtual void OnOpened()
        {
        }

        protected virtual void OnLoaded()
        {
        }

        protected virtual void OnUnloaded()
        {
        }

        protected virtual void Close()
        {
            CancelEventArgs args = new CancelEventArgs();
            this.OnClosing(args);
            if(!args.Cancel)
            {
                this.OnClosed();
            }
        }

        protected virtual void OnClosing(CancelEventArgs args)
        {
            if (this.Closing != null)
            {
                this.Closing(this, args);
            }
        }

        protected virtual void OnClosed()
        {
            if (this.Closed != null)
            {
                this.Closed(this, EventArgs.Empty);
            }
        }
    }
}
